package com.hugeyurt.service.impl;

import com.hugeyurt.mapper.CourseMapper;
import com.hugeyurt.po.EnrollCourse;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EnrollCouseMQ {
    @Resource
    private CourseMapper courseMapper;

    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(value = "course-queue"),
                    exchange = @Exchange(value = "course-exchange",type="fanout"))
    )
    public void handleMessage(@Payload HashMap<String, String> map, Channel channel,
                              @Headers Map<String, Object> headers) {
        System.out.println("消费消息："+map.toString());
        try{
            Thread.sleep(10*1000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        EnrollCourse enrollCourse = new EnrollCourse();
        enrollCourse.setCno(Integer.parseInt(map.get("cno")));
        enrollCourse.setSno(map.get("sno"));
        enrollCourse.setTime(getTime());
        courseMapper.saveEnrollCourse(enrollCourse);
        Long tag=(Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(tag,false); //true为批量确认，false为单条确认
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}